﻿if (typeof jQuery == 'undefined')
{
	throw "You must have a reference to jQuery.";
}

; (function($) {
	
	$.fn.navigation = function(options)
	{
		var $this = this;
		var sliding = false;
		var currentItem = null;
		var subNavigation = new Array();

		options = $.extend({}, $.fn.navigation.defaults, options);

		return $this.each(function()
		{
			var $element = $(this);

			var CloseHeaderSubNavigation = function()
			{
				if (!sliding)
				{
					sliding = true;

					$(options.subNavContainer).slideUp(options.slideSpeed, function()
					{
						sliding = false;
					});

					currentItem = null;
				}
			}

			$($element).click(function(e)
			{
				var ajaxUrl = $(this).attr('data');
				var loadedAttr = $(this).data('loaded');

				var FillItemData = function(data)
				{
					subNavigation[ajaxUrl] = data;
				}

				var ShowSubNavigation = function()
				{
					if (!sliding)
					{
						if (currentItem == null || currentItem != ajaxUrl)
						{
							sliding = true;
							currentItem = ajaxUrl;

							$(options.subNavContainer).slideDown(options.slideSpeed, function()
							{
								sliding = false;
							});

							$(options.subNavContent).html(subNavigation[ajaxUrl]);
						}
						else
						{
							CloseHeaderSubNavigation();
						}
					}
				}

				if (!loadedAttr)
				{
					$(options.subNavContent).ajaxLoading(
					{
						ajaxUrl: ajaxUrl,
						clearContent: options.clearHtmlWhileLoading,
						onOverlayOpen: ShowSubNavigation,
						onAjaxSuccess: FillItemData
					});

					$(this).data('loaded', true);
				}
				else
				{
					ShowSubNavigation();
				}

				e.preventDefault();
			});

			$(options.closeButtonContainer + ' a').click(function(e)
			{
				CloseHeaderSubNavigation();

				e.preventDefault();
			});
		});
	};

	$.fn.navigation.defaults =
	{
		subNavContainer: '#HeaderSubNavigation',
		subNavContent: '.headerSubNavContent',
		closeButtonContainer: '.headerSubNavClose',
		clearHtmlWhileLoading: true,
		slideSpeed: 400
	};
})(jQuery);